import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/KeepAliveWidget/KeepAliveWidget.dart';
import 'package:orginone/config/theme/UIConfig.dart';
import 'package:orginone/components/EmptyWidget/EmptyWidget.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/base/storages/storage.dart';
import 'package:orginone/dart/core/public/entity.dart';
import 'package:orginone/pages/portal/assets_management/assets_module/asset_select_modal.dart';
import 'package:provider/provider.dart';
import '../../../dart/core/chat/activity.dart';
import 'model.dart';

class EntitySwitchWidget<T extends IEntity> extends StatefulWidget {
  EntitySwitchModel<T> data;
  Widget? empty;
  Future<Widget> Function(T data) buildChildren;

  EntitySwitchWidget(
      {Key? key, required this.data, required this.buildChildren, this.empty})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _DataSwitchState<T>();
}

class _DataSwitchState<T extends IEntity> extends State<EntitySwitchWidget<T>> {
  EntitySwitchModel<T> get data => widget.data;
  Widget? get empty => widget.empty;
  Future<Widget> Function(T data) get buildChildren => widget.buildChildren;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return KeepAliveWidget(
        child: ChangeNotifierProvider(
      create: (context) => data,
      child: FutureBuilder<T?>(
          future: data.initData(),
          builder: (BuildContext context, AsyncSnapshot<T?> shot) {
            if (shot.connectionState == ConnectionState.done) {
              if (shot.hasData) {
                return _buildBody(context);
              } else {
                return empty ?? EmptyWidget();
              }
            }
            return const Center(
              child: CircularProgressIndicator(),
            );
          }),
      // lazy: true,
      // builder: (BuildContext subContext, Widget? child) {
      //   return FutureBuilder<T>(
      //       builder: (BuildContext context, AsyncSnapshot<T> shot) {
      //     if (shot.hasData && shot.connectionState == ConnectionState.done) {
      //       return _buildBody(context);
      //     }
      //     return const CircularProgressIndicator();
      //   });
      // }
    ));
  }

  Widget _buildBody(BuildContext context) {
    return Column(
      children: [
        Container(
          color: XColors.white,
          child: buildSelectApp(context, data.datas),
        ),
        const Divider(
          // indent: 60,
          thickness: 1,
          height: 1,
        ),
        Expanded(
            child: Container(
                color: XColors.bgListBody,
                child: Consumer<EntitySwitchModel<T>>(
                  builder: (context, dataSwitchModel, child) {
                    return FutureBuilder<Widget>(
                      builder: (context, snapshot) {
                        if (snapshot.connectionState == ConnectionState.done) {
                          if (snapshot.hasData) {
                            return snapshot.data ?? EmptyWidget();
                          } else {
                            return empty ?? EmptyWidget();
                          }
                        }
                        return const Center(
                          child: CircularProgressIndicator(),
                        );
                      },
                      future: Future(() {
                        bool isswitchView = Storage.getBool('switchflag');
                        if (!isswitchView) {
                          if (null != dataSwitchModel.currData) {
                            return buildChildren(dataSwitchModel.currData!);
                          }
                        } else {
                          if (null != data.currData) {
                            return buildChildren(data.currData!);
                          }
                        }
                        return empty ?? EmptyWidget();
                      }),
                    );
                  },
                )))
      ],
    );
  }

  void moveItemToTop(List<IActivity> items, IActivity itemToMove) {
    int index = items.indexOf(itemToMove);
    if (index != -1) {
      items.removeAt(index);
      items.insert(0, itemToMove);
    }
  }

  buildSelectApp(BuildContext context, List<T> list) {
    IActivity? allActivity;
    List<IActivity> iactivityDatas = [];
    if (list.isNotEmpty) {
      for(var iActivity in list) {
        if ((iActivity as IActivity).activityList.isNotEmpty) {
          iactivityDatas.add(iActivity);
          if (iActivity.name == "全部") {
            allActivity = iActivity;
          }
        }
      }
      if (iactivityDatas.isNotEmpty) {
        iactivityDatas.sort((a, b) {
          return DateTime.parse(a.metadata.createTime ?? "")
              .compareTo(DateTime.parse(b.metadata.createTime ?? ""));
        });
        moveItemToTop(iactivityDatas, allActivity!);
      }
    }
    bool switchflag = Storage.getBool('switchflag');
    return Container(
        padding: const EdgeInsets.all(16),
        color: Colors.white,
        width: UIConfig.screenWidth,
        child: Row(
          children: [
            Expanded(
              child: Consumer<EntitySwitchModel<T>>(
                builder: (context, dataSwitchModel, child) {
                  return SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          XImage.entityIcon(switchflag ? data.currData : dataSwitchModel.currData,
                              size: Size(45.w, 45.w), radius: 4),
                          Padding(
                            padding: const EdgeInsets.only(left: 8),
                            child: Text(switchflag ? data.currData?.name ?? '' : dataSwitchModel.currData?.name ?? '',
                                textAlign: TextAlign.center,
                                overflow: TextOverflow.ellipsis,
                                style: XFonts.size24Black0W700),
                          )
                        ],
                      ));
                },
              ),
            ),
            const SizedBox(width: 4),
            GestureDetector(
              onTap: () {
                showSearchApplication(context, /*("动态" == data.title) ? iactivityDatas : */iactivityDatas,
                    title: "切换${data.title}",
                    hint: "搜索", onSelected: (selectData) async {
                  context.read<EntitySwitchModel<T>>().currData = selectData[0];
                  Storage.setBool('switchflag', false);
                  // loadApp();
                  setState(() {});
                  // await relationCtrl.user!.updateCurrentSpace(selectData[0].id);
                });
              },
              child: Row(
                children: [
                  Text('切换${data.title}', style: XFonts.size22Black0),
                  const Icon(
                    Icons.arrow_forward_ios,
                    size: 18,
                  )
                ],
              ),
            )
          ],
        ));
  }
}
